'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { CartItem, getCart } from '@/lib/cart';

interface CartContextType {
  cartItems: CartItem[];
  totalItems: number;
  refreshCart: () => Promise<void>;
  isLoading: boolean;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

interface CartProviderProps {
  children: ReactNode;
  sessionId: string;
}

export function CartProvider({ children, sessionId }: CartProviderProps) {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  const refreshCart = async () => {
    if (!sessionId) return;
    
    setIsLoading(true);
    try {
      const items = await getCart(sessionId);
      setCartItems(items);
    } catch (error) {
      console.error('Failed to refresh cart:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    refreshCart();
  }, [sessionId]);

  const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0);

  return (
    <CartContext.Provider value={{ 
      cartItems, 
      totalItems, 
      refreshCart, 
      isLoading 
    }}>
      {children}
    </CartContext.Provider>
  );
}

export function useCart() {
  const context = useContext(CartContext);
  if (context === undefined) {
    throw new Error('useCart must be used within a CartProvider');
  }
  return context;
}